﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Objects.Factory.Support;

namespace TinyERP.Framework.Plugin
{
    public abstract class PluginContext
    {
        public abstract void RegisterModuleObjects();

        protected void RegisterDALObject(Type daoType)
        {
            RegisterDALObject(daoType.Name, daoType);
        }

        protected void RegisterDALObject(string objectName, Type daoType)
        {
            IObjectDefinitionFactory objectDefinitionFactory = new DefaultObjectDefinitionFactory();
            ObjectDefinitionBuilder builder = ObjectDefinitionBuilder.RootObjectDefinition(objectDefinitionFactory, daoType);
            builder.AddPropertyReference("HibernateTemplate", "HibernateTemplate");
            ServiceLocator.GetInstance().RegisterObject(objectName, builder.ObjectDefinition);
        }

        protected void RegisterServiceObject(Type serviceType, string[] propertyRefs)
        {
            RegisterServiceObject(serviceType.Name, serviceType, propertyRefs);
        }


        protected void RegisterServiceObject(string objectName, Type serviceType, string[] propertyRefs)
        {
            RegisterRealObjectService(objectName, serviceType, propertyRefs);
            RegisterProxyObject(objectName);
        }

        private void RegisterRealObjectService(string objectName, Type serviceType, string[] propertyRefs)
        {
            IObjectDefinitionFactory objectDefinitionFactory = new DefaultObjectDefinitionFactory();
            ObjectDefinitionBuilder builder = ObjectDefinitionBuilder.RootObjectDefinition(objectDefinitionFactory, serviceType);
            if (propertyRefs != null)
            {
                foreach (string propertyReference in propertyRefs)
                {
                    builder.AddPropertyReference(propertyReference, propertyReference);
                }
            }
            ServiceLocator.GetInstance().RegisterObject(objectName, builder.ObjectDefinition);
        }
        private void RegisterProxyObject(string serviceObjectName)
        {
            IObjectDefinitionFactory objectDefinitionFactory = new DefaultObjectDefinitionFactory();
            ObjectDefinitionBuilder builder = ObjectDefinitionBuilder.ChildObjectDefinition(objectDefinitionFactory, "TxProxyConfigurationTemplate");
            builder.AddPropertyReference("Target", serviceObjectName);
            ServiceLocator.GetInstance().RegisterObject(serviceObjectName + "Proxy", builder.ObjectDefinition);
        }
    }
}
